package com.example.demo.controller.usercontroller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.Result;

import com.example.demo.context.UserContext;
import com.example.demo.entity.Consultation;
import com.example.demo.service.ConsultationService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 咨询表(Consultation)表控制层
 *
 * @author makejava
 * @since 2025-01-28 12:36:46
 */
@RestController
@RequestMapping("user/consultation")
public class ConsultationController {
    /**
     * 服务对象
     */
    @Resource
    private ConsultationService consultationService;
    @GetMapping("list")
    public Result<List<Consultation>> list() {
        return Result.success(consultationService.listAll());
    }


    @PostMapping("create")
    public Result<Consultation> create(@RequestBody Consultation consultation) {
        // 设置初始状态
        consultation.setStatus(0);
        consultation.setCreateTime(new Date());

        // 验证必填字段
        if (consultation.getExpertId() == null ||
                consultation.getChildId() == null ||
                consultation.getUserId() == null ||
                StringUtils.isBlank(consultation.getTitle()) ||
                StringUtils.isBlank(consultation.getContent()) ||
                StringUtils.isBlank(consultation.getConsultationType())) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }

        // 验证咨询类型
        String type = consultation.getConsultationType();
        if (!Arrays.asList("growth", "nutrition", "psychology", "other")
                .contains(type)) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }

        // 验证标题长度
        if (consultation.getTitle().length() > 100) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        consultation.setUserId(UserContext.getUserId());
        // 保存问诊记录
        consultationService.save(consultation);
        return Result.success(consultation);
    }
}

